<?php
namespace Shared\LRC\Metadata\Parsers;

/**
 * @package Translation
 * @version 1.0.0.0
 * @author J.Minchev
 * @internal 
 * @todo
 */
class Translation implements ParserI {

    /**
     * @var string
     */
    private $classname;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $EntityManager;

    /**
     * @var \Doctrine\Common\Annotations\Reader
     */
    private $Reader;

    public function __construct($classname, \Doctrine\ORM\EntityManager $EntityManager) {
        $this->classname = $classname;
        $this->EntityManager = $EntityManager;
        
        $this->Reader = \Shared\Application::instance()->getAnnotationReader();
        
//        $this->Reader = $this->EntityManager->getConfiguration()->getMetadataDriverImpl()->getReader();
//        $this->Reader = new \Doctrine\Common\Annotations\AnnotationReader();
    }

    /**
     * @throws \Shared\LRC\Metadata\Parsers\NotPropertyMappedEntityException
     * @return \Shared\LRC\Metata\TranslationMetadata
     */
    public function parse() {
        $ClassMetadataFactory = $this->EntityManager->getMetadataFactory();
        $ClassMetadata = $ClassMetadataFactory->getMetadataFor($this->classname);

        $EntityAnnotation = $this->Reader->getClassAnnotation($ClassMetadata->getReflectionClass(), '\Shared\LRC\Annotations\Translation');
        if (!$EntityAnnotation) {
            throw new NotPropertyMappedEntityException('No LRC\Annotations\Translation class annotation found for class ' . $this->classname);
        }

        foreach ($ClassMetadata->getReflectionClass()->getProperties() as $Property) {
            $annotations = $this->Reader->getPropertyAnnotations($Property);
            foreach ($annotations as $Annotation) {
                if ($Annotation instanceof \Shared\LRC\Annotations\Object) {
                    $objectPropertyName = $Property->name;
                } else if ($Annotation instanceof \Shared\LRC\Annotations\Language) {
                    $languagePropertyName = $Property->name;
                }
            }
        }
        if (!$objectPropertyName) {
            throw new NotPropertyMappedEntityException('No LRC\Annotations\Object property annotation found in ' . $this->classname);
        } else if (!$languagePropertyName) {
            throw new NotPropertyMappedEntityException('No\Shared\LRC\Annotations\Language property annotation found in ' . $this->classname);
        }
        return new \Shared\LRC\Metadata\TranslationMetadata($objectPropertyName, $languagePropertyName);
    }

}